package com.sky.service.impl;

import com.sky.common.ResponseResult;
import com.sky.domain.LoginUser;
import com.sky.domain.User;
import com.sky.service.LoginService;
import com.sky.utils.JwtUtil;
import com.sky.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        // AuthenticationManager的authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 如果认证没通过，提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误!");
        }
        // 认证通过返回jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(userId.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwt);
        // 将jwt存入redis中
        redisCache.setCacheObject("login:"+userId,loginUser,5, TimeUnit.MINUTES);
        return new ResponseResult(200,"登录成功！",map);
    }

    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder中的id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        // 删除redis中userId
        String redisKey = "login:"+userId;
        redisCache.deleteObject(redisKey);

        return new ResponseResult(200,"注销成功！");
    }
}
